<template>
  <div class="recipe-detail-container">
    <!-- 顶部导航栏 -->
    <div class="recipe-header">
      <div class="back-button" @click="goBack">
        <van-icon name="arrow-left" />
        <span>返回</span>
      </div>
      <div class="header-title">食谱详情</div>
      <div class="header-actions">
        <van-icon
          :name="isCollected ? 'star' : 'star-o'"
          :class="{ collected: isCollected }"
          @click="toggleCollection"
        />
        <van-icon name="share-o" @click="shareRecipe" />
      </div>
    </div>

    <!-- 主内容 -->
    <div class="recipe-content" v-if="recipe.id">
      <!-- 食谱封面图 -->
      <div class="recipe-image-container">
        <img :src="recipe.imageUrl || defaultImage" class="recipe-image" />

        <!-- 食谱标签 -->
        <div class="recipe-tags">
          <van-tag type="primary" v-if="recipe.flavor">{{
            recipe.flavor
          }}</van-tag>
          <van-tag type="success">{{ difficultyText }}</van-tag>
          <van-tag type="warning" v-if="recipe.duration"
            >{{ recipe.duration }}分钟</van-tag
          >
        </div>
      </div>

      <!-- 食谱基本信息 -->
      <div class="recipe-info-section">
        <h1 class="recipe-title">{{ recipe.name }}</h1>
        <div class="recipe-meta">
          <div class="author">
            <van-icon name="manager-o" />
            <span>{{ recipe.author || "佚名" }}</span>
          </div>
          <div class="rating">
            <van-rate
              v-model="avgRating"
              readonly
              allow-half
              size="16"
              color="#ff6000"
              void-color="#eee"
            />
            <span>{{ avgRating.toFixed(1) }}</span>
            <span class="rating-count">({{ ratingCount }}人评价)</span>
          </div>
          <div class="view-count">
            <van-icon name="eye-o" />
            <span>{{ formatNumber(recipe.viewCount || 0) }}次浏览</span>
          </div>
        </div>

        <div class="recipe-description">
          {{ recipe.description }}
        </div>
      </div>

      <!-- 用户评分区域 -->
      <div class="user-rating-section">
        <div class="section-title">
          <h2>我的评分</h2>
        </div>
        <div class="user-rating-content">
          <van-rate
            v-model="userRatingValue"
            size="24"
            color="#ff6000"
            void-color="#eee"
            @change="rateRecipe"
          />
          <span class="rating-text">{{ ratingText }}</span>
        </div>
      </div>

      <!-- 食材列表 -->
      <div class="ingredients-section">
        <div class="section-title">
          <h2>食材清单</h2>
        </div>
        <div class="ingredients-list">
          <div
            v-for="(ingredient, index) in ingredients"
            :key="index"
            class="ingredient-item"
          >
            <span class="ingredient-name">{{ ingredient.name }}</span>
            <span class="ingredient-amount"
              >{{ ingredient.amount }}{{ ingredient.unit }}</span
            >
          </div>
        </div>
      </div>

      <!-- 步骤说明 -->
      <div class="steps-section">
        <div class="section-title">
          <h2>烹饪步骤</h2>
        </div>
        <div class="steps-list">
          <div v-for="(step, index) in steps" :key="index" class="step-item">
            <div class="step-number">{{ index + 1 }}</div>
            <div class="step-content">
              <div class="step-text">{{ step.description }}</div>
              <img
                v-if="step.imageUrl"
                :src="step.imageUrl"
                class="step-image"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 评价列表 -->
      <div class="ratings-section">
        <div class="section-title">
          <h2>用户评价 ({{ ratings.length }})</h2>
        </div>
        <div class="ratings-list" v-if="ratings.length > 0">
          <div
            v-for="(rating, index) in ratings"
            :key="index"
            class="rating-item"
          >
            <div class="rating-header">
              <div class="rating-user">
                <img
                  :src="rating.user?.avatar || defaultAvatar"
                  class="user-avatar"
                />
                <span>{{
                  rating.user?.nickname || rating.user?.username || "匿名用户"
                }}</span>
              </div>
              <div class="rating-value">
                <van-rate
                  v-model="rating.rating"
                  readonly
                  size="14"
                  color="#ff6000"
                  void-color="#eee"
                />
                <span class="rating-date">{{
                  formatDate(rating.createTime)
                }}</span>
              </div>
            </div>
            <div class="rating-comment" v-if="rating.comment">
              {{ rating.comment }}
            </div>
          </div>
        </div>
        <div class="no-ratings" v-else>暂无评价，快来发表你的看法吧！</div>
      </div>
    </div>

    <!-- 评价弹窗 -->
    <van-popup
      v-model="showRatingPopup"
      round
      position="bottom"
      :style="{ height: '40%' }"
    >
      <div class="rating-popup">
        <div class="popup-header">
          <div class="popup-title">评价食谱</div>
          <van-icon name="close" @click="showRatingPopup = false" />
        </div>
        <div class="rating-form">
          <div class="rating-stars">
            <van-rate
              v-model="userRatingValue"
              size="36"
              color="#ff6000"
              void-color="#eee"
            />
            <div class="rating-text">{{ ratingText }}</div>
          </div>
          <van-field
            v-model="ratingComment"
            type="textarea"
            placeholder="分享你的烹饪体验吧"
            rows="4"
            maxlength="200"
            show-word-limit
          />
          <div class="popup-buttons">
            <van-button type="primary" block round @click="submitRating">
              提交评价
            </van-button>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 加载状态 -->
    <div class="loading-container" v-if="loading">
      <van-loading type="spinner" color="#1989fa" size="36px" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showToast, showDialog } from "vant";
import { useUserStore } from "@/stores/userStore";
import {
  getRecipeDetail,
  getRecipeSteps,
  getRecipeIngredients,
  collectRecipe,
  uncollectRecipe,
  checkCollection,
  rateRecipe,
  getRecipeAverageRating,
  getUserRating,
  getRecipeRatings,
  recordViewHistory,
} from "@/api/recipe";
import defaultImage from "@/assets/default-recipe.jpg";
import defaultAvatar from "@/assets/default-avatar.jpg";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 状态变量
const recipe = ref({});
const steps = ref([]);
const ingredients = ref([]);
const ratings = ref([]);
const loading = ref(true);
const isCollected = ref(false);
const avgRating = ref(0);
const ratingCount = ref(0);
const userRatingValue = ref(0);
const ratingComment = ref("");
const showRatingPopup = ref(false);

// 浏览记录计时
const viewStartTime = ref(Date.now());
const viewDuration = ref(0);

// 计算属性
const recipeId = computed(() => Number(route.params.id));
const difficultyText = computed(() => {
  const map = {
    1: "简单",
    2: "普通",
    3: "困难",
  };
  return map[recipe.value.difficulty] || "普通";
});
const ratingText = computed(() => {
  const texts = ["很差", "较差", "一般", "不错", "很棒"];
  return texts[Math.floor(userRatingValue.value) - 1] || "请评分";
});

// 方法
const goBack = () => {
  router.back();
};

const fetchRecipeDetail = async () => {
  try {
    loading.value = true;
    const { data } = await getRecipeDetail(recipeId.value);
    recipe.value = data;
  } catch (error) {
    showToast("获取食谱详情失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const fetchRecipeSteps = async () => {
  try {
    const { data } = await getRecipeSteps(recipeId.value);
    steps.value = data;
  } catch (error) {
    console.error("获取步骤失败", error);
  }
};

const fetchRecipeIngredients = async () => {
  try {
    const { data } = await getRecipeIngredients(recipeId.value);
    ingredients.value = data;
  } catch (error) {
    console.error("获取食材失败", error);
  }
};

const checkUserCollection = async () => {
  if (!userStore.isLoggedIn) return;

  try {
    const { data } = await checkCollection(userStore.userId, recipeId.value);
    isCollected.value = data;
  } catch (error) {
    console.error("检查收藏状态失败", error);
  }
};

const toggleCollection = async () => {
  if (!userStore.isLoggedIn) {
    showDialog({
      title: "提示",
      message: "请先登录后再收藏食谱",
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      showCancelButton: true,
    }).then(() => {
      router.push("/login");
    });
    return;
  }

  try {
    if (isCollected.value) {
      await uncollectRecipe(userStore.userId, recipeId.value);
      showToast("已取消收藏");
    } else {
      await collectRecipe(userStore.userId, recipeId.value);
      showToast("收藏成功");
    }
    isCollected.value = !isCollected.value;
  } catch (error) {
    showToast("操作失败，请稍后重试");
    console.error(error);
  }
};

const fetchRecipeRatings = async () => {
  try {
    const { data } = await getRecipeRatings(recipeId.value);
    ratings.value = data;
    ratingCount.value = data.length;
  } catch (error) {
    console.error("获取评价失败", error);
  }
};

const fetchAverageRating = async () => {
  try {
    const { data } = await getRecipeAverageRating(recipeId.value);
    avgRating.value = data || 0;
  } catch (error) {
    console.error("获取平均评分失败", error);
  }
};

const fetchUserRating = async () => {
  if (!userStore.isLoggedIn) return;

  try {
    const { data } = await getUserRating(userStore.userId, recipeId.value);
    if (data) {
      userRatingValue.value = data.rating;
      ratingComment.value = data.comment || "";
    }
  } catch (error) {
    console.error("获取用户评分失败", error);
  }
};

const rateRecipe = () => {
  if (!userStore.isLoggedIn) {
    showDialog({
      title: "提示",
      message: "请先登录后再评分",
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      showCancelButton: true,
    }).then(() => {
      router.push("/login");
    });
    userRatingValue.value = 0;
    return;
  }

  showRatingPopup.value = true;
};

const submitRating = async () => {
  try {
    await rateRecipe(
      userStore.userId,
      recipeId.value,
      userRatingValue.value,
      ratingComment.value
    );
    showToast("评价成功");
    showRatingPopup.value = false;

    // 刷新评价和平均分
    fetchRecipeRatings();
    fetchAverageRating();
  } catch (error) {
    showToast("评价失败，请稍后重试");
    console.error(error);
  }
};

const shareRecipe = () => {
  showToast("分享功能开发中");
};

const formatNumber = (num) => {
  if (num < 1000) return num;
  return (num / 1000).toFixed(1) + "k";
};

const formatDate = (dateStr) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
};

const recordView = async () => {
  if (!userStore.isLoggedIn) return;

  const duration = Math.floor((Date.now() - viewStartTime.value) / 1000);
  if (duration > 5) {
    // 只记录超过5秒的浏览
    viewDuration.value = duration;
    try {
      await recordViewHistory(userStore.userId, recipeId.value, duration);
    } catch (error) {
      console.error("记录浏览历史失败", error);
    }
  }
};

// 生命周期钩子
onMounted(async () => {
  viewStartTime.value = Date.now();
  await fetchRecipeDetail();
  await Promise.all([
    fetchRecipeSteps(),
    fetchRecipeIngredients(),
    fetchRecipeRatings(),
    fetchAverageRating(),
    fetchUserRating(),
    checkUserCollection(),
  ]);
});

onBeforeUnmount(() => {
  recordView();
});
</script>

<style scoped>
.recipe-detail-container {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 24px;
}

/* 头部导航 */
.recipe-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.back-button {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.back-button .van-icon {
  margin-right: 4px;
}

.header-title {
  font-weight: bold;
  font-size: 18px;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.header-actions .van-icon {
  font-size: 24px;
  cursor: pointer;
}

.collected {
  color: #ff6000;
}

/* 食谱内容 */
.recipe-content {
  padding: 0 0 24px;
}

.recipe-image-container {
  position: relative;
  width: 100%;
  height: 250px;
}

.recipe-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.recipe-tags {
  position: absolute;
  bottom: 12px;
  left: 12px;
  display: flex;
  gap: 8px;
}

.recipe-info-section {
  background-color: #fff;
  padding: 20px 16px;
  margin-bottom: 12px;
}

.recipe-title {
  font-size: 22px;
  font-weight: bold;
  margin: 0 0 12px;
  color: #333;
}

.recipe-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
}

.recipe-meta .van-icon {
  margin-right: 4px;
  vertical-align: -2px;
}

.rating-count {
  margin-left: 2px;
}

.recipe-description {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
}

/* 用户评分区域 */
.user-rating-section {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 12px;
}

.section-title {
  margin-bottom: 12px;
  border-left: 4px solid #ff6000;
  padding-left: 8px;
}

.section-title h2 {
  font-size: 18px;
  font-weight: bold;
  margin: 0;
  color: #333;
}

.user-rating-content {
  display: flex;
  align-items: center;
}

.rating-text {
  margin-left: 8px;
  color: #ff6000;
  font-size: 14px;
}

/* 食材列表 */
.ingredients-section {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 12px;
}

.ingredients-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.ingredient-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 6px;
}

.ingredient-name {
  font-weight: 500;
}

.ingredient-amount {
  color: #666;
}

/* 步骤列表 */
.steps-section {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 12px;
}

.steps-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.step-item {
  display: flex;
}

.step-number {
  width: 24px;
  height: 24px;
  background-color: #ff6000;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
}

.step-text {
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 12px;
}

.step-image {
  width: 100%;
  border-radius: 8px;
  height: auto;
}

/* 评价列表 */
.ratings-section {
  background-color: #fff;
  padding: 16px;
}

.ratings-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.rating-item {
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.rating-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.rating-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.rating-user {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
}

.rating-date {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.rating-comment {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

.no-ratings {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

/* 评价弹窗 */
.rating-popup {
  padding: 16px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
}

.rating-stars {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.popup-buttons {
  margin-top: 20px;
}

/* 加载状态 */
.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

/* 响应式 */
@media (min-width: 768px) {
  .recipe-image-container {
    height: 350px;
  }

  .recipe-info-section,
  .user-rating-section,
  .ingredients-section,
  .steps-section,
  .ratings-section {
    max-width: 800px;
    margin-left: auto;
    margin-right: auto;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }

  .ingredients-list {
    grid-template-columns: repeat(3, 1fr);
  }
}
</style>
